#include "netCloud_mySql.h"
#include <my_header.h>

//使用方式MYSQL * mysql;&mysql
int  netCloud_mysql_init(MYSQL **pthreadSql){
    *pthreadSql = mysql_init(NULL);
    if (*pthreadSql == NULL) {
        printf("mysql_init() failed\n");
        return -1; // 初始化失败
    }
    return 0; // 成功
}

int  netCloud_mysql_connect(MYSQL *pthreadSql,char *host, char *user, char *password, char *db, unsigned int port){
    if (mysql_real_connect(pthreadSql, host, user, password, db, port, NULL, 0) == NULL) {
        printf("mysql_real_connect() failed: %s\n", mysql_error(pthreadSql));
        mysql_close(pthreadSql);
        return -1; // 连接失败
    }
    return 0; // 成功
}

int  netCloud_mysql_close(MYSQL *pthreadSql){
    mysql_close(pthreadSql);
    return 0;
}

int  netCloud_mysql_insert(MYSQL *pthreadSql,SQL_TABLE_NAME tb_name, const char* sql_insert){
    char sql_statement[1024] = {0};
    switch (tb_name) {
        case SQL_USER:
            snprintf(sql_statement, sizeof(sql_statement), "INSERT INTO user_table (id, username, password) VALUES (%s)", sql_insert);
            break;
        case SQL_VIRTUE_FILE:
            snprintf(sql_statement, sizeof(sql_statement), "INSERT INTO virtue_file_table (id, filename, owner_id, parent_directory_id, hash, filetype, filepath, is_deleted) VALUES %s", sql_insert);
            printf("sql_statement: %s\n", sql_statement);
            break;
        default:
            return -1; // 不可以
    }
    int qret=mysql_query(pthreadSql, sql_statement);
    if(qret != 0){
        printf("mysql_query() failed: %s\n", mysql_error(pthreadSql));
        return -1; 
    }
    return 0; 
}

int netCloud_mysql_select(SQL_TABLE_NAME tb_name, MYSQL *pthreadSql, const char *sql_select, char *result_buffer, int buffer_size)
{
    MYSQL_RES *res = NULL;
    MYSQL_ROW row;
    int ret = -1;
    int offset = 0;
    char query[1024] = {0}; 


    if (!pthreadSql || !result_buffer || buffer_size <= 0)
    {
        printf("[ERROR] Invalid parameters: pthreadSql=%p, buffer=%p, size=%d\n",
               pthreadSql, result_buffer, buffer_size);
        return -1;
    }

    const char *table_name = NULL;
    switch (tb_name)
    {
    case SQL_VIRTUE_FILE:
        table_name = "virtue_file_table";
        break;
    case SQL_USER:
        table_name = "user_table";
        break;
    default:
        printf("[ERROR] Unsupported table type: %d\n", tb_name);
        return -1;
    }


    const char *columns = sql_select ? sql_select : "*";
    int query_len = snprintf(query, sizeof(query),
                           "SELECT %s FROM %s",
                           columns, table_name);

    if (query_len >= sizeof(query))
    {
        printf("[ERROR] Query string truncated (max %zu bytes)\n", sizeof(query));
        return -1;
    }

    printf("[DEBUG] Executing SQL: %s\n", query);

    if (mysql_query(pthreadSql, query) != 0)
    {
        printf("[ERROR] Query failed: %s\n", mysql_error(pthreadSql));
        return -1;
    }

    res = mysql_store_result(pthreadSql);
    if (!res)
    {
        printf("[ERROR] Store result failed: %s\n", mysql_error(pthreadSql));
        return -1;
    }


    unsigned int num_fields = mysql_num_fields(res);
    unsigned long num_rows = mysql_num_rows(res);

        //可选是否输出列名，行列数据
    // offset += snprintf(result_buffer + offset, buffer_size - offset,
    //                  "Total: %lu rows, %u columns\n",
    //                  num_rows, num_fields);


    // MYSQL_FIELD *fields = mysql_fetch_fields(res);
    // for (unsigned int i = 0; i < num_fields && offset < buffer_size - 1; i++)
    // {
    //     offset += snprintf(result_buffer + offset, buffer_size - offset,
    //                      "%s\t", fields[i].name);
    // }
    // if (offset < buffer_size - 1)
    // {
    //     result_buffer[offset++] = '\n';
    // }

    /* 写入数据行 */
    while ((row = mysql_fetch_row(res)) && (offset < buffer_size - 1))
    {
        for (unsigned int i = 0; i < num_fields && offset < buffer_size - 1; i++)
        {
            offset += snprintf(result_buffer + offset, buffer_size - offset,
                             "%s\t", row[i] ? row[i] : "NULL");
        }
        if (offset < buffer_size - 1)
        {
            result_buffer[offset++] = '\n';
        }
    }

    /* 缓冲区检查 */
    if (offset >= buffer_size - 1)
    {
        printf("[WARN] Result truncated at %d bytes (buffer size=%d)\n", 
               offset, buffer_size);
    }

    /* 释放资源 */
    mysql_free_result(res);
    return 0;
}
